package servlet.other;

import org.apache.commons.dbutils.QueryRunner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@WebServlet(name = "DownloadServlet", urlPatterns = "/wk07/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    //通过连接访问只能是get请求了
    public void doGet(HttpServletRequest request, HttpServletResponse
            response) throws ServletException, IOException {
        //设置ContentType字段值
        response.setContentType("text/html;charset=utf-8");
        //获取所要下载的文件路径
        String filename = request.getParameter("filePath");
        //下载文件真实名
        String downFile = filename.substring(filename.lastIndexOf("/") + 1);
        // 通知浏览器以下载的方式打开
        response.addHeader("Content-Type", "application/octet-stream");
        response.addHeader("Content-Disposition",
                "attachment;filename=" + downFile);
        // 通过文件流读取文件
        InputStream in = getServletContext().getResourceAsStream(filename);
        // 想查看文件根路径，使用这个:                     System.out.println(getServletContext().getRealPath("/"));
        // 获取response对象的输出流
        OutputStream out = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        //循环取出流中的数据
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai", "root", "123456");
            QueryRunner queryRunner = new QueryRunner();
//            file_path唯一,可以这么写
            int update = queryRunner.update(connection, "update file set download=download+1 where file_path=?", filename);
            if (update > 0) {
                System.out.println("下载成功!");
            } else {
                System.out.println("下载失败!");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //HttpSession session = request.getSession();
        //int power = Integer.parseInt(session.getAttribute("power").toString());
        ////带着power跳转,否则报错!
        //response.sendRedirect("fileSystem.jsp?power=" + power);
    }


    public void doPost(HttpServletRequest request, HttpServletResponse
            response) throws ServletException, IOException {

    }
}